import React, {useEffect, useMemo, useState} from 'react'
import {Button, Input, message as antdMessage, Space, Switch, Table, Tag} from 'antd'

function usePolling(url, interval = 1000) {
    const [data, setData] = useState(null)
    const [error, setError] = useState(null)
    useEffect(() => {
        let mounted = true
        let timer = null

        async function tick() {
            try {
                const res = await fetch(url)
                const json = await res.json()
                if (mounted) setData(json)
            } catch (e) {
                if (mounted) setError(e)
            } finally {
                timer = setTimeout(tick, interval)
            }
        }

        tick()
        return () => {
            mounted = false;
            if (timer) clearTimeout(timer)
        }
    }, [url, interval])
    return {data, error}
}

export default function App() {
    const {data: dashboard} = usePolling('/api/dashboard?limit=150', 1000)
    const [kwInput, setKwInput] = useState('')
    const [previewOn, setPreviewOn] = useState(false)
    const [previewRawUrl, setPreviewRawUrl] = useState('')
    const [previewCleanUrl, setPreviewCleanUrl] = useState('')

    // 从统一接口中提取状态和消息数据
    const status = dashboard?.status
    const msgs = dashboard?.messages

    const columns = [
        {title: '时间', dataIndex: 'time', width: 170, fixed: 'left'},
        {title: '名称', dataIndex: 'name', width: 250, render: v => <Tag color="geekblue">{v || '未知'}</Tag>},
        {
            title: '内容',
            dataIndex: 'msg',
            ellipsis: {
                showTitle: false,
            },
            render: (text) => (
                <div style={{
                    wordBreak: 'break-all',
                    whiteSpace: 'normal',
                    lineHeight: '1.4'
                }}>
                    {text}
                </div>
            )
        },
    ]

    async function start() {
        const r = await fetch('/api/start', {method: 'POST'})
        if (r.ok) antdMessage.success('监控已启动'); else antdMessage.error('启动失败')
    }

    async function stop() {
        const r = await fetch('/api/stop', {method: 'POST'})
        if (r.ok) antdMessage.success('监控已停止'); else antdMessage.error('停止失败')
    }

    async function saveKw() {
        const arr = (kwInput || '').split(',').map(s => s.trim()).filter(Boolean)
        const r = await fetch('/api/keywords', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({keywords: arr})
        })
        if (r.ok) {
            antdMessage.success('关键词已更新')
        } else {
            antdMessage.error('更新失败')
        }
    }

    // 同步关键词输入框
    useEffect(() => {
        if (status?.keywords) {
            setKwInput(status.keywords.join(','))
        }
    }, [status?.keywords])

    // 同步后端状态的 debug 开关
    useEffect(() => {
        if (status && typeof status.debug_preview === 'boolean') {
            setPreviewOn(status.debug_preview)
        }
    }, [status])

    // 轮询预览图像：仅当开关开启且后端已有可用预览时才轮询，避免 404 噪音
    const stages = status?.preview_stages || {raw: false, cleaned: false, ocr: false}
    const canPollRaw = previewOn && !!stages.raw
    const canPollClean = previewOn && !!stages.cleaned
    const canPollOcr = previewOn && !!stages.ocr
    useEffect(() => {
        let timer = null

        function tick() {
            const ts = Date.now()
            if (canPollRaw) setPreviewRawUrl(`/api/preview/raw?t=${ts}`)
            if (canPollClean) setPreviewCleanUrl(`/api/preview/cleaned?t=${ts}`)
            timer = setTimeout(tick, 800)
        }

        tick()
        if (!canPollRaw) setPreviewRawUrl('')
        if (!canPollClean) setPreviewCleanUrl('')
        return () => {
            if (timer) clearTimeout(timer)
        }
    }, [canPollRaw, canPollClean, canPollOcr])

    const hits = useMemo(() => (msgs?.hits || []).slice().sort((a, b) => (b.time || '').localeCompare(a.time || '')).slice(0, 150), [msgs])
    const all = useMemo(() => (msgs?.all || []).slice().sort((a, b) => (b.time || '').localeCompare(a.time || '')).slice(0, 150), [msgs])

    return (
        <div className="container">
            <div className="card">
                <div className="title">星痕共鸣 · 消息监控仪表盘</div>
                <Space wrap>
                    <Button type="primary" onClick={start}>启动监控</Button>
                    <Button danger onClick={stop}>停止监控</Button>
                    <Input style={{width: 360}} value={kwInput} onChange={e => setKwInput(e.target.value)}
                           placeholder="关键词，逗号分隔"/>
                    <Button onClick={saveKw}>保存关键词</Button>
                    <span>{status?.running ? '状态：运行中' : '状态：已停止'}</span>
                    <span>{`命中条数：${status?.hit_count ?? 0}`}</span>
                    <span>{`消息条数：${status?.all_count ?? 0}`}</span>
                    <span>
            调试预览：<Switch size="small" checked={previewOn} onChange={async (checked) => {
                        setPreviewOn(checked)
                        try {
                            await fetch('/api/debug_preview', {
                                method: 'POST',
                                headers: {'Content-Type': 'application/json'},
                                body: JSON.stringify({enable: checked})
                            })
                            antdMessage.success(checked ? '调试预览已开启' : '调试预览已关闭')
                        } catch (e) {
                            antdMessage.error('操作失败')
                        }
                    }}/>
          </span>
                </Space>
            </div>

            {/* 调试区域：仅在开启预览时展示 */}
            {previewOn && (
                <div className="card">
                    <div className="title">调试区域</div>
                    <div className="grid" style={{width: "100%", display: "flex"}}>
                        <div className="card" style={{width: "100%"}}>
                            <div className="grid" style={{gridTemplateColumns: '1fr', gap: 12}}>
                                <div>
                                    <div style={{marginBottom: 6, color: '#9aa4bf'}}>原图 + 检测框</div>
                                    {stages.raw ? (
                                        <img src={previewRawUrl} alt="debug-raw" style={{
                                            width: '100%',
                                            height: 260,
                                            objectFit: 'contain',
                                            background: '#000',
                                            display: 'block'
                                        }}/>
                                    ) : (
                                        <div style={{
                                            height: 260,
                                            background: '#000',
                                            color: '#888',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center'
                                        }}>等待原图阶段...</div>
                                    )}
                                </div>
                                <div>
                                    <div style={{marginBottom: 6, color: '#9aa4bf'}}>清理后（裁剪堆叠）</div>
                                    {stages.cleaned ? (
                                        <img src={previewCleanUrl} alt="debug-cleaned" style={{
                                            width: '100%',
                                            height: 260,
                                            objectFit: 'contain',
                                            background: '#000',
                                            display: 'block'
                                        }}/>
                                    ) : (
                                        <div style={{
                                            height: 260,
                                            background: '#000',
                                            color: '#888',
                                            display: 'flex',
                                            alignItems: 'center',
                                            justifyContent: 'center'
                                        }}>等待清理阶段...</div>
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* 消息区域 */}
            <div className="card">
                <div className="card">
                    <div className="title">命中关键词</div>
                    <Table rowKey={(r, i) => 'h' + i} columns={columns} dataSource={hits}
                           pagination={false} scroll={{y: 360}}/>
                </div>
                <div className="card">
                    <div className="title">全部最新消息</div>
                    <Table rowKey={(r, i) => 'a' + i} columns={columns} dataSource={all}
                           pagination={false} scroll={{y: 360}}/>
                </div>
            </div>

            <div style={{textAlign: 'center', color: '#8a8a8a', marginTop: 12}}>© {new Date().getFullYear()} XHGM
                Monitor
            </div>
        </div>
    )
}
